<?php
namespace catcher\platform\order;

use catcher\facade\Http;
use Spatie\ArrayToXml\ArrayToXml;

class Kaspi {
    private $url;
    private $lastError = '';
    private $token = '';

    public function __construct($token)
    {
        $this->url = "https://kaspi.kz/shop/api/v2/";
        $this->headers = [
            'X-Auth-Token: '.$token,
//            'Content-Type: application/vnd.api+json'
        ];
    }

    public function getLastError() { return $this->lastError; }

    /**
     * 拉取订单列表
     * @param $startTime
     * @param $endTime
     * @param string $status
     * @param int $start
     * @param int $limit
     * @return mixed
     */
    public function getOrders($startTime, $endTime, $status = 'APPROVED_BY_BANK', $start = 0, $limit = 10)
    {
//        $startTime = '1747975664851';
//        $endTime = '1747981590934';
        $params = [
            'page[number]' => $start,
            'page[size]' => $limit,
//            'filter[orders][state]' => 'NEW',
            'filter[orders][creationDate][$ge]' => $startTime,
            'filter[orders][creationDate][$le]' => $endTime,
            'filter[orders][status]' => $status,
//            'filter[orders][deliveryType]' => 'DELIVERY',
//            'include[orders]' => 'user'
        ];

        $curl = curl_init();
        curl_setopt_array($curl,[
            CURLOPT_URL => $this->url . 'orders?'.http_build_query($params),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $this->headers
        ]);
        $response = curl_exec($curl);
        $error = curl_error($curl);
        $httpcode = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if(curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);
        }

        curl_close($curl);
        // 解析 JSON 响应
        $result = json_decode($response,true);
        return $result;
    }


    /**
     * 拉取订单商品信息
     * @param $startTime
     * @param $endTime
     * @param string $status
     * @param int $start
     * @param int $limit
     * @return mixed
     */
    public function getEntries($orderId)
    {
        $curl = curl_init();
        curl_setopt_array($curl,[
            CURLOPT_URL => $this->url . 'orders/'.$orderId.'/entries',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $this->headers
        ]);
        $response = curl_exec($curl);
        $error = curl_error($curl);
        $httpcode = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if(curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);
        }

        curl_close($curl);
        // 解析 JSON 响应
        $result = json_decode($response,true);
        return $result;
    }

}

